package com.crm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.crm.pojo.SysUser;
import com.crm.service.SysUserService;
import com.crm.service.impl.SysUserServiceImpl;

public class LoginServlet extends HttpServlet {
	SysUserService userService = new SysUserServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String flag = req.getParameter("flag");
		if(flag.equals("login")) {
			login(req,resp);
		}
		if(flag.equals("edit")) {
			edit(req,resp);
		}
		
	}

	private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = req.getSession();
		session.removeAttribute("userName");
		resp.sendRedirect(req.getContextPath()+"/login.jsp");
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String txtName = req.getParameter("txtName");
		String txtPwd = req.getParameter("txtPwd");
		boolean flag = userService.loginUser(txtName,txtPwd);
		if(flag) {
			SysUser user = userService.queryUser(txtName);
			HttpSession session = req.getSession();
			session.setAttribute("userName", user.getUserName());
			resp.sendRedirect(req.getContextPath()+"/index.jsp");
		}else {
			resp.sendRedirect(req.getContextPath()+"/login.jsp");
		}
	}

}
